package com.adobe.apprise.commands
{
	import com.adobe.apprise.database.DatabaseResponder;
	import com.adobe.apprise.database.DatabaseEvent;
	import com.adobe.apprise.model.ModelLocator;
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.apprise.events.RefreshCountsEvent;
	
	public class MarkAllReadCommand implements ICommand
	{
		public function execute(ce:CairngormEvent):void
		{
			var postIds:Array = new Array();
			for each (var post:Object in ModelLocator.getInstance().posts)
			{
				if (!post.read)
				{
					post.read = true;
					ModelLocator.getInstance().posts.itemUpdated(post, "read");
					postIds.push(post.id);
				}
			}
			this.markAsRead(postIds);
		}
		
		private function markAsRead(postIds:Array):void
		{
			if (postIds == null || postIds.length == 0)
			{
				new RefreshCountsEvent().dispatch();
				return;
			}
			var postId:Number = postIds.shift();
			var responder:DatabaseResponder = new DatabaseResponder();
			responder.addEventListener(DatabaseEvent.RESULT_EVENT,
				function(e:DatabaseEvent):void
				{
					markAsRead(postIds);
				});
			ModelLocator.getInstance().db.updatePostReadFlag(responder, postId, true);
		}
	}
}
